package com.engine.salary.service.impl;

import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.constant.SalaryDefaultTenantConstant;
import com.engine.salary.entity.salaryacct.po.SalaryAcctRecordPO;
import com.engine.salary.entity.taxagent.param.TaxAgentSaveBaseParam;
import com.engine.salary.entity.taxagent.po.TaxAgentBasePO;
import com.engine.salary.enums.SalaryOnOffEnum;
import com.engine.salary.enums.salaryaccounting.SalaryAcctRecordStatusEnum;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.mapper.taxagent.TaxAgentBaseMapper;
import com.engine.salary.service.SIAccountService;
import com.engine.salary.service.SalaryAcctRecordService;
import com.engine.salary.service.TaxAgentBaseService;
import com.engine.salary.sys.entity.vo.UploadConfigResponse;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import com.engine.salary.util.db.IdGenerator;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.hrm.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 个税扣缴义务人基本信息
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
public class TaxAgentBaseServiceImpl extends Service implements TaxAgentBaseService {

    private TaxAgentBaseMapper getTaxAgentBaseMapper() {
        return MapperProxyFactory.getProxy(TaxAgentBaseMapper.class);
    }

    private SalaryAcctRecordService getSalaryAcctRecordService(User user) {
        return ServiceUtil.getService(SalaryAcctRecordServiceImpl.class, user);
    }

    private SIAccountService getSIAccountService(User user) {
        return ServiceUtil.getService(SIAccountServiceImpl.class, user);
    }

    public TaxAgentBaseServiceImpl() {
    }

    @Override
    public Boolean isOpenDevolution() {
        TaxAgentBasePO base = getBaseInfo();
        return (base != null && base.getDevolutionStatus() == 1) ? Boolean.TRUE : Boolean.FALSE;
    }

    @Override
    public TaxAgentBasePO getBaseInfo() {
        List<TaxAgentBasePO> list = getTaxAgentBaseMapper().listAll();
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    @Override
    public String save(TaxAgentSaveBaseParam saveBaseParam) {
        if (saveBaseParam.getDevolutionStatus() == null) {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(84026, "参数错误"));
        }
        // 检查使用中的数据
        boolean isUnable = checkUsedData();
        if (isUnable) {
            if (saveBaseParam.getDevolutionStatus()) {
                throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(117395, "当前有未归档的核算数据，全部归档后才可以启用分权"));
            } else {
                throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(117396, "当前有未归档的核算数据，全部归档后才可以停用分权"));
            }
        }
        TaxAgentBasePO base = getBaseInfo();
        Date now = new Date();
        Integer devolutionStatus = saveBaseParam.getDevolutionStatus() ? SalaryOnOffEnum.ON.getValue() : SalaryOnOffEnum.OFF.getValue();
        if (base == null) {
            getTaxAgentBaseMapper().insertIgnoreNull(
                    TaxAgentBasePO.builder()
                            .id(IdGenerator.generate())
                            .devolutionStatus(devolutionStatus)
                            .createTime(now)
                            .updateTime(now)
                            .creator((long) user.getUID())
                            .tenantKey(SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY)
                            .build());
        } else {
            base.setUpdateTime(now);
            base.setDevolutionStatus(devolutionStatus);
            getTaxAgentBaseMapper().updateIgnoreNull(base);
        }
        return StringUtils.EMPTY;
    }

    @Override
    public TaxAgentBasePO getConfig() {
        Date now = new Date();
        TaxAgentBasePO baseInfo = getBaseInfo();
        if (baseInfo == null) {
            baseInfo = TaxAgentBasePO.builder()
                    .id(IdGenerator.generate())
                    .devolutionStatus(0)
                    .createTime(now)
                    .updateTime(now)
                    .creator((long) user.getUID())
                    .tenantKey(SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY)
                    .build();
        }
        return baseInfo;
    }

    @Override
    public UploadConfigResponse.Result parseConfig(TaxAgentBasePO config) {
        UploadConfigResponse.Result result = UploadConfigResponse.Result.builder().message("分权配置加载完毕")
                .success(new ArrayList<>())
                .warning(new ArrayList<>())
                .error(new ArrayList<>())
                .build();
        TaxAgentBasePO baseInfo = getBaseInfo();
        if (baseInfo == null) {
            config.setCreator((long) user.getUID());
            getTaxAgentBaseMapper().insertIgnoreNull(config);
        } else {
            baseInfo.setDevolutionStatus(config.getDevolutionStatus());
            getTaxAgentBaseMapper().updateIgnoreNull(baseInfo);
        }
        result.getSuccess().add("分权加载完毕，分权" + (config.getDevolutionStatus() == 1 ? "开启" : "关闭 "));
        return result;
    }

    /**
     * 检查是否有未归档数据
     *
     * @return
     */
    private boolean checkUsedData() {
        // 检查是否核算
        // todo 1.社保福利档案是否有核算未归档
        Boolean checkedValue = false;//= getSIAccountService(user).changeAdminUnfiledCheck();
        // todo 2.薪资核算是否有核算未归档
        List<SalaryAcctRecordPO> salaryAcctRecords = getSalaryAcctRecordService(user).listByStatus(SalaryAcctRecordStatusEnum.NOT_ARCHIVED);// getSalaryAcctRecordService(user).listByStatusAndEmployeeId(SalaryAcctRecordStatusEnum.NOT_ARCHIVED, currentTenantKey);
        if (CollectionUtils.isNotEmpty(salaryAcctRecords) || checkedValue) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
